//
//  SearchListController.m
//  MedicineBox
//
//  Created by dllo on 15/9/19.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "SearchListController.h"
#import "AsyncConnection.h"
#import "SearchListCell.h"
#import "SearchPurchaseController.h"
#import "MJRefreshAutoNormalFooter.h"
#import "MJRefreshNormalHeader.h"
#import "DKNightVersion.h"
@interface SearchListController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, assign) int count;
@property (nonatomic, retain) UITabBarController *tab;
@property (nonatomic, retain) UINavigationController *nav;
@property (nonatomic, retain) UILabel *titleLabel;
@property (nonatomic, retain) NSMutableArray *tableArray;
@property (nonatomic, retain) UITableView *listTableView;

@end

@implementation SearchListController

- (void)dealloc
{
    
    [_tab release];
    [_nav release];
    [_titleLabel release];
    [_tableArray release];
    [_listTableView release];
    [super dealloc];
    
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.tableArray = [NSMutableArray array];
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.view.nightBackgroundColor = UIColorFromRGB(0x343434);
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 5, 20, 20);
    [backButton setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"iconfont-fanhui-3" ofType:@"png"]] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.listTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 60) style:UITableViewStyleGrouped];
    self.listTableView.dataSource = self;
    self.listTableView.delegate = self;
    _listTableView.nightBackgroundColor = UIColorFromRGB(0x343434);
    _listTableView.nightSeparatorColor = UIColorFromRGB(0x313131);
    [self.view addSubview:_listTableView];
    [_listTableView release];
    
    
}

- (void)backButtonAction:(id)sender
{

    [self.navigationController popViewControllerAnimated:YES];

}

- (void)getUrl:(NSString *)url dic:(NSDictionary *)dic
{

    NSString *catalogId = [dic objectForKey:@"content"];
    NSArray *array = [catalogId componentsSeparatedByString:@"="];
    catalogId = [array objectAtIndex:1];
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 5, self.view.frame.size.width - 120, 40)];
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.nightTextColor = [UIColor whiteColor];
    _titleLabel.font = [UIFont systemFontOfSize:20];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = _titleLabel;
    [_titleLabel release];
    _titleLabel.text = [dic objectForKey:@"name"];
    [AsyncConnection asyncConnectionWithUrl:url name:nil parameters:nil block:^(id data) {
        
        NSDictionary *dic = [[data objectForKey:@"data"] objectForKey:@"item_list_resp_info"];
        NSArray *array = [dic objectForKey:@"hits"];
        [self.tableArray addObjectsFromArray:array];
        [self.listTableView reloadData];
        
    } get:@"post"];
    [self shuaXinAddJiaZai:catalogId];
   
    
}

- (void)shuaXinAddJiaZai:(NSString *)urlId
{
    
    self.count = 1;
    
   NSString *url = [NSString stringWithFormat:@"http://mobi.111.com.cn/ApiControl?method=products.getlist.news&method=products.getlist.news&isDesc=1&sort=0&province=9&pageindex=1&pagesize=10&catalogId=%@&encryptversion=2&sign=5BEBF94B15FB772D6547C140CF097F45&timestamp=20150918190421&os=android&venderId=2011102716210000&signmethod=md5&format=json&type=mobile&channelName=huawei&versionName=4.6.1&versionCode=477&screensize=480*854&width=480&height=854",urlId];
   
    self.listTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [AsyncConnection asyncConnectionWithUrl:url name:nil parameters:nil block:^(id data) {
            
            NSDictionary *dic = [[data objectForKey:@"data"] objectForKey:@"item_list_resp_info"];
            NSArray *array = [dic objectForKey:@"hits"];
            [_tableArray removeAllObjects];
            [self.tableArray addObjectsFromArray:array];
            [self.listTableView reloadData];
            
        } get:@"post"];
        
        NSLog(@"刷新完成");
        [self.listTableView reloadData];
        [self.listTableView.header endRefreshing];
        
    }];
    
    
    
    self.listTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        _count++;
        NSString *url2 = [NSString stringWithFormat:@"http://mobi.111.com.cn/ApiControl?method=products.getlist.news&method=products.getlist.news&isDesc=1&sort=0&province=9&pageindex=%d&pagesize=10&catalogId=%@&encryptversion=2&sign=5BEBF94B15FB772D6547C140CF097F45&timestamp=20150918190421&os=android&venderId=2011102716210000&signmethod=md5&format=json&type=mobile&channelName=huawei&versionName=4.6.1&versionCode=477&screensize=480*854&width=480&height=854",_count,urlId];
        [AsyncConnection asyncConnectionWithUrl:url2 name:nil parameters:nil block:^(id data) {
            
            NSDictionary *dic = [[data objectForKey:@"data"] objectForKey:@"item_list_resp_info"];
            NSArray *array = [dic objectForKey:@"hits"];
            [self.tableArray addObjectsFromArray:array];
            [self.listTableView reloadData];
            
        } get:@"post"];
        
        [self.listTableView.footer endRefreshing];
    }];
    
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.tableArray.count / 2;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
   static NSString *searchL = @"list";
    SearchListCell *search = [tableView dequeueReusableCellWithIdentifier:searchL];
    if (search == nil) {
        
        
        search = [[SearchListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:searchL];
        
    }
    if (_tableArray.count != 0) {
        
        [search getDic:[_tableArray objectAtIndex:indexPath.row * 2] dic:[_tableArray objectAtIndex:indexPath.row * 2 + 1]];
        
    }
    search.nightBackgroundColor = UIColorFromRGB(0x343434);
    search.target = self;
    search.action = @selector(tapAction:);
    return search;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.view.frame.size.width < 375) {
        
        return 220;
        
    } if (self.view.frame.size.width == 375) {
        
        return 240;
        
    }
    else {
    
        return 260;
    
    }
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

- (void)getTab:(UITabBarController *)tab nav:(UINavigationController *)nav
{

    self.tab = tab;
    self.nav = nav;

}

- (void)tapAction:(NSDictionary *)dic
{

    self.tab.tabBar.hidden = YES;
    NSDictionary *tempDic = [dic objectForKey:@"product"];
    NSString *str = [NSString stringWithFormat:@"http://mobi.111.com.cn/ApiControl?method=products.getbaseinfo&itemcode=%@&flag=0&province=9&encryptversion=2&sign=01DE5C022E6E01EF39A79B2A4569D308&timestamp=20150918190726&os=android&venderId=2011102716210000&signmethod=md5&format=json&type=mobile&channelName=huawei&versionName=4.6.1&versionCode=477&screensize=480*854&width=480&height=854",[tempDic objectForKey:@"id"]];
    SearchPurchaseController *searchPC = [[SearchPurchaseController alloc] init];
    [searchPC getSearchUrl:str tab:self.tab nav:self.nav dic:tempDic];
    [self.navigationController pushViewController:searchPC animated:YES];
    [searchPC release];
    

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
